package com.d404.server;

import java.io.IOException;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;

import com.alibaba.fastjson.JSON;

import im.beans.AddNewFriends;
import manager.PersistentManager;

/**
 * Servlet implementation class GetFriendRequest
 */
//@WebServlet("/GetFriendRequest")
public class GetFriendRequest extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public GetFriendRequest() {
        super();
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//		response.getWriter().append("Served at: ").append(request.getContextPath());
		request.setCharacterEncoding("UTF-8");
		List<AddNewFriends> anfs = null;
		String userID = request.getParameter("userID");
		
		SessionFactory sf = PersistentManager.sharemanager().getSessionFactory();
//		Session session = sf.openSession();
		Session session = sf.getCurrentSession();
		Transaction tx = session.beginTransaction();
		try
		{
			Query q2 = session.createQuery("from AddNewFriends anf where anf.be_asked_id = ? and anf.state = ?");
			q2.setParameter(0, Long.parseLong(userID));
			q2.setParameter(1, AddFriend.MsgBack.State.WAIT_TO_BE_DEALED);
			anfs = q2.list();
			session.getTransaction().commit();
		}catch(Exception e)
		{
			tx.rollback();
			e.printStackTrace();
		}
		finally {
//			session.close();
		}
		
		System.out.println(JSON.toJSONString(anfs));
		response.setCharacterEncoding("UTF-8");
		response.getWriter().append(JSON.toJSONString(anfs));
		
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doGet(request, response);
	}

}
